package server.users;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import json.JSONObjectWrapper;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import server.database.DatabaseColumn;
import server.database.DatabaseService;
import server.database.query.IQueryResult;
import server.servlet.AbstractServlet;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

public class AuthorizationServlet extends AbstractServlet
{
	private static final long serialVersionUID = 1512128824378883250L;

	public static final String PATH = API + "/authorization";

	@Override
	protected void doGetSpecific(HttpServletRequest request, HttpServletResponse response, JSONObject output) throws ServletException, IOException
	{
		IQueryResult queryResult = null;

		List<DatabaseColumn> lstFields = Lists.newArrayList(UsersTable.ROLE);
		List<String> lstValues = Lists.newArrayList(UsersServlet.NOT_AUTHORIZED);

		queryResult = getTable().getAllEntities(lstFields, lstValues, UsersTable.AND);

		output.put(QUERY_RESULT, queryResult.getResult());
		if (queryResult.getResult() == IQueryResult.SUCESS)
		{
			output.put(RESULT, true);

			JSONArray entities = new JSONArray();
			buildEntityValues(queryResult.getResultValues(), entities, getTable());

			output.put(UsersServlet.USERS, entities);

		}
		else if (queryResult.getResult() != IQueryResult.NO_RESULTS)
		{
			setFail(output, UNEXPECTED_ERROR, UNEXPECTED_ERROR);
		}
	}

	@Override
	protected void doPostSpecific(JSONObjectWrapper request, JSONObject output) throws ServletException, IOException
	{
		UsersTable users = getTable();

		String sID = request.getStringValue(UsersTable.ID.getName());
		String sRole = request.getStringValue(UsersTable.ROLE.getName());

		Map<DatabaseColumn, String> mpValues = Maps.newHashMap();
		mpValues.put(UsersTable.ROLE, sRole);

		IQueryResult queryResult = users.update(sID, mpValues);
		if (queryResult.getResult() == IQueryResult.SUCESS)
		{
			output.put(RESULT, true);
		}
		else
		{
			setFail(output, UNEXPECTED_ERROR, queryResult.getError());
		}
	}

	@Override
	protected UsersTable getTable()
	{
		return (UsersTable) DatabaseService.getInstance().getTable(UsersTable.TABLE_NAME);
	}

}
